package com.wxy.netty.黏包半包处理;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;

import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 47868
 */
public class Client2 {
    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    // 复用Scanner，避免频繁创建和关闭
    private static Scanner scanner = new Scanner(System.in);

    public static String getString() {
        while (true) { // 循环直到输入合法
            String str = scanner.nextLine();
            if (str.length() < 10) {
                StringBuilder sb = new StringBuilder(str);
                for (int i = 0; i < 10 - str.length(); i++) {
                    sb.append("_");
                }
                return sb.toString();
            } else {
                System.out.println("参数异常，请重新输入（长度需小于10）...");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        // 只添加日志处理器，不需要自定义OutboundHandler
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                })
                .connect("127.0.0.1", 8888)
                .sync()
                .channel();

        executorService.submit(() -> {
            int isExit = 0;
            while (true) {
                try {
                    ByteBuf buf = channel.alloc().buffer();
                    for (int i = 0; i < 5; i++) {
                        String content = getString();
                        if (content.equals("exit______")){
                            channel.writeAndFlush(buf).sync();
                            channel.close().sync();
                            isExit = 1;
                            break;
                        }
                        buf.writeBytes(content.getBytes(CharsetUtil.UTF_8));
                        System.out.println("已发送：" + content);
                    }
                    if (isExit == 1) {
                        break;
                    }
                    channel.writeAndFlush(buf).sync(); // 主动触发写操作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 等待连接关闭后释放资源
        channel.closeFuture().addListener(future -> {
            group.shutdownGracefully();
            executorService.shutdown();
            }
        );
    }
}